package com.cgm.common;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;

/**
 * 
 */
public class WxOSSClient {

	private OSSClient ossClient;

	private String accessKeyId;
	private String accessKeySecret;
	private String endpoint;
	private String bucketName;

	public WxOSSClient(){}
	public WxOSSClient(String endpoint, String bucketName, String accessKeyId, String accessKeySecret) {
		this.endpoint = endpoint;
		this.accessKeyId = accessKeyId;
		this.accessKeySecret = accessKeySecret;
		this.bucketName = bucketName;
	}

	public void init() {
		ClientConfiguration conf = new ClientConfiguration();
		conf.setMaxConnections(10);
		conf.setConnectionTimeout(5000);
		conf.setMaxErrorRetry(3);
		conf.setSocketTimeout(2000);
		ossClient = new OSSClient(endpoint, getAccessKeyId(), getAccessKeySecret(), conf);
		if (!ossClient.doesBucketExist(bucketName)) {
			ossClient.createBucket(bucketName);
		}

	}

	public void cleanUp() {
		// ossClient.
	}

	public List<String> listFiles(String parentPath) {

		List<String> fileList = new ArrayList<String>();
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		listObjectsRequest.setPrefix(parentPath + "/");
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		for (OSSObjectSummary objectSummary : listing.getObjectSummaries()) {
			fileList.add(objectSummary.getKey());
		}
		return fileList;
	}

	public List<String> listDirs(String parentPath) {
		List<String> fileList = new ArrayList<String>();
		// 构造ListObjectsRequest请求
		ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
		// "/" 为文件夹的分隔符
		listObjectsRequest.setDelimiter("/");
		// 列出fun目录下的所有文件和文件夹
		if (parentPath != null && parentPath.length() > 0) {
			listObjectsRequest.setPrefix(parentPath + "/");
		}
		ObjectListing listing = ossClient.listObjects(listObjectsRequest);
		// 遍历所有CommonPrefix
		for (String commonPrefix : listing.getCommonPrefixes()) {
			fileList.add(commonPrefix);
		}

		return fileList;
	}

	public void uploadFile(String destFileDir, String destFileName, String sourceFilePath)
			throws FileNotFoundException {

		putObject(destFileDir, destFileName, sourceFilePath);

	}

	/**
	 * 上传Object,小文件;
	 * 
	 * @param ossClient
	 * @param bucketName
	 * @param destFileName
	 * @param sourceFilePath
	 * @throws FileNotFoundException
	 */
	public PutObjectResult putObject(String destFileDir, String destFileName, String sourceFilePath)
			throws FileNotFoundException {

		// 获取指定文件的输入流
		File file = new File(sourceFilePath);
		InputStream content = new FileInputStream(file);
		// 创建上传Object的Metadata
		ObjectMetadata meta = new ObjectMetadata();
		// 必须设置ContentLength
		meta.setContentLength(file.length());
		// 上传Object.
		PutObjectResult result = ossClient.putObject(bucketName, destFileDir + "/" + destFileName, content, meta);
		try {
			content.close();
		} catch (Exception e) {
		}
		return result;

	}

	/**
	 * 大文件上传;
	 * 
	 * @param key
	 * @param filePath
	 * @throws IOException
	 */
	public void multipartUpload(String key, String filePath) throws IOException {
		InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(bucketName,
				key);
		InitiateMultipartUploadResult initiateMultipartUploadResult = ossClient
				.initiateMultipartUpload(initiateMultipartUploadRequest);
		// 打印UploadId

		// 设置每块为 5M
		final int partSize = 1024 * 1024 * 5;
		File partFile = new File(filePath);
		// 计算分块数目
		int partCount = (int) (partFile.length() / partSize);
		if (partFile.length() % partSize != 0) {
			partCount++;
		}
		// 新建一个List保存每个分块上传后的ETag和PartNumber
		List<PartETag> partETags = new ArrayList<PartETag>();
		for (int i = 0; i < partCount; i++) {
			// 获取文件流
			FileInputStream fis = new FileInputStream(partFile);
			// 跳到每个分块的开头
			long skipBytes = partSize * i;
			fis.skip(skipBytes);
			// 计算每个分块的大小
			long size = partSize < partFile.length() - skipBytes ? partSize : partFile.length() - skipBytes;
			// 创建UploadPartRequest，上传分块
			UploadPartRequest uploadPartRequest = new UploadPartRequest();
			uploadPartRequest.setBucketName(bucketName);
			uploadPartRequest.setKey(key);
			uploadPartRequest.setUploadId(initiateMultipartUploadResult.getUploadId());
			uploadPartRequest.setInputStream(fis);
			uploadPartRequest.setPartSize(size);
			uploadPartRequest.setPartNumber(i + 1);
			UploadPartResult uploadPartResult = ossClient.uploadPart(uploadPartRequest);
			// 将返回的PartETag保存到List中。
			partETags.add(uploadPartResult.getPartETag());
			// 关闭文件
			fis.close();
		}
	}

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getEndpoint() {
		return endpoint;
	}

	public void setEndpoint(String endpoint) {
		this.endpoint = endpoint;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

}
